package com.nononsenseapps.feeder.db.room

import androidx.room.*
import cn.ekuma.odbo.mobile.room.BaseDao
import com.nononsenseapps.feeder.db.entity.FeedItemTag
import kotlinx.coroutines.flow.Flow

@Dao
interface FeedItemTagDao: BaseDao<FeedItemTag> {

    @Query("SELECT * FROM feed_item_tag")
    fun listAll(): Flow<List<FeedItemTag>>

    @Query("SELECT * FROM feed_item_tag where hot IS :hot")
    fun listHotItemTag(hot:Boolean = true): Flow<List<FeedItemTag>>

    @Query("SELECT count(*) FROM feed_item_tag")
    fun count():Long

    @Query("SELECT count(*) FROM feed_item_tag where name = :name")
    fun exits(name: String): Boolean

    @Query("UPDATE feed_item_tag SET name = :newName where name = :oldName ")
    fun updateByName(oldName: String, newName: String)

    @Query("UPDATE feed_item_tag SET parent_tag = :newName where parent_tag = :oldName  ")
    fun updateByParentName(oldName: String, newName: String)

    @Query("UPDATE feed_item_tag SET attention_level = :attentionLevel where id = :id ")
    fun updateFeedItemTagAttentionLevel(id: Long, attentionLevel: Int)

    @Query("UPDATE feed_item_tag SET hot = :hot where id = :id ")
    fun updateItemTagHot(id : Long, hot : Boolean)

    @Query("UPDATE feed_item_tag SET click_count = :count where id = :id ")
    fun updateFeedItemTagClickCount(id: Long, count: Int)

}

/**
 * Inserts or updates feed depending on if ID is valid. Returns ID.
 */
fun FeedItemTagDao.upsert(feedItemTag: FeedItemTag): Long = when (feedItemTag.id > ID_UNSET) {
    true -> {
        update(feedItemTag)
        feedItemTag.id
    }
    false -> {
        val id=insert(feedItemTag)
        feedItemTag.id=id
        id
    }
}